package com.zllkj.mm.module.shopping.fragment

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.MenuItem
import androidx.recyclerview.widget.LinearLayoutManager
import com.alipay.sdk.app.PayTask
import com.github.gzuliyujiang.wheelpicker.OptionPicker
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionPickedListener
import com.kennyc.bottomsheet.BottomSheetListener
import com.kennyc.bottomsheet.BottomSheetMenuDialogFragment
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.zllkj.mm.MyApp
import com.zllkj.mm.R
import com.zllkj.mm.adapter.OrderConfirmListAdapter
import com.zllkj.mm.api.network.RetrofitHelper
import com.zllkj.mm.api.network.RxHelper
import com.zllkj.mm.api.network.subscriber.ProgressSubscriber
import com.zllkj.mm.base.BaseTitleFragment
import com.zllkj.mm.common.L
import com.zllkj.mm.model.entity.*
import com.zllkj.mm.module.home.fragments.MyAddressListFragment
import com.zllkj.mm.module.shopping.vm.ItemMyAddressListVM
import com.zllkj.mm.module.shopping.vm.ItemShoppingCartIListVM
import com.zllkj.mm.util.JsonUtil
import com.zllkj.mm.util.PayResult
import com.zllkj.mm.util.common.AppUtils
import kotlinx.android.synthetic.main.fragment_order_confirm.view.*
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.set
import kotlin.concurrent.thread


class OrderConfirmFragment(val datas:List<ItemShoppingCartIListVM>) :BaseTitleFragment() {
    lateinit var listAdapter : OrderConfirmListAdapter
    var addressBeanVo =  ItemMyAddressListVM()

    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                1-> {
                    val payResult = PayResult(msg.obj as Map<String?, String?>)
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo: String = payResult.getResult() // 同步返回需要验证的信息
                    val resultStatus: String = payResult.getResultStatus()
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        L.showToast("支付成功")
                        removeFragment()
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        L.showToast("支付失败")
                    }
                }
            }
        }
    }

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_order_confirm
    }

    override fun onResume() {
        super.onResume()
        var addressBean = AppUtils.getFragmentData("addressItem")
        addressBean?.let { data ->
            addressBeanVo = data as ItemMyAddressListVM
            mRootView?.tv_order_detail_name?.text = addressBeanVo?.name
            mRootView?.tv_order_detail_phone?.text = addressBeanVo?.phone
            mRootView?.tv_order_detail_address?.text =addressBeanVo?.address
        }
    }

    fun createOrder(){
        var orderCreateReqList = arrayOfNulls<OrderDetailReqVo>(datas.size)
        datas.mapIndexed { index, it ->
            var orderList = ArrayList<OrderGoods>()
            it.goodsList.map {
                var orderGoods = OrderGoods(it.goodsNum,it.goodsId)
                orderList.add(orderGoods)
            }
            var orderCreateReq = OrderDetailReqVo(
                    0,orderList,addressBeanVo?.id!!.toInt(),"123",it.shopId.toInt())
            orderCreateReqList[index] = orderCreateReq
        }


        addSubscribe(RetrofitHelper.getInstance().orderApi.createOrder((HashMap<String, Any>().apply {
            this["orderDetails"] = JsonUtil.GsonString(orderCreateReqList).replace("\"", "")
        })).compose<CreateOrderResp>(RxHelper.defaultHandleResult<CreateOrderResp>()).subscribe(object : ProgressSubscriber<CreateOrderResp>(context){
            override fun onSucc(t:CreateOrderResp) {
                var listener = object : BottomSheetListener {
                    override fun onSheetDismissed(bottomSheet: BottomSheetMenuDialogFragment, `object`: Any?, dismissEvent: Int) {

                    }

                    override fun onSheetItemSelected(bottomSheet: BottomSheetMenuDialogFragment, item: MenuItem, `object`: Any?) {
                        if(item.itemId == R.id.menu_alipay) {
                            getPayData(0,t?.orderIds)
                        } else {
                            getPayData(1,t?.orderIds)
                        }
                    }

                    override fun onSheetShown(bottomSheet: BottomSheetMenuDialogFragment, `object`: Any?) {

                    }

                }
                BottomSheetMenuDialogFragment.Builder(context = requireContext(),
                        sheet = R.menu.menu_pay_bottom_sheet,
                        listener = listener,
                        title = "请选择支付方式",
                        `object` = "")
                        .show(childFragmentManager)

            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }
        }))
    }

    fun getPayData(payType:Int,orderId:String){
        if (payType == 0) {
            addSubscribe(RetrofitHelper.getInstance().orderApi.getAliPayOrderInfo((HashMap<String, Any>().apply {
                this["orderIds"] = orderId
                this["orderSource"] = 0
            })).compose<String>(RxHelper.defaultHandleResult<String>()).subscribe(object : ProgressSubscriber<String>(context){
                override fun onSucc(t:String) {
                    thread {
                       kotlin.run {
                           val alipay = PayTask(requireActivity())
                           val result = alipay.payV2(t, true)

                           val msg = Message()
                           msg.what = 1
                           msg.obj = result
                           mHandler.sendMessage(msg)
                       }
                    }.start()

                }

                override fun onError(e: Throwable?) {
                    super.onError(e)
                }
            }))
        } else {
            addSubscribe(RetrofitHelper.getInstance().orderApi.getWeChatPayOrderInfo((HashMap<String, Any>().apply {
                this["orderIds"] = orderId
                this["orderSource"] = 0
            })).compose<WeChatPayResp>(RxHelper.defaultHandleResult<WeChatPayResp>()).subscribe(object : ProgressSubscriber<WeChatPayResp>(context){
                override fun onSucc(t:WeChatPayResp) {
                    thread {
                        var req = PayReq()
                        req.timeStamp = t?.timestamp
                        req.sign = t?.sign
                        req.appId = MyApp.wxAppId
                        req.prepayId = t?.prepayid
                        req.packageValue = "Sign=WXPay"
                        req.nonceStr = t?.noncestr
                        val api = WXAPIFactory.createWXAPI(requireContext(), null, false)
                        api.sendReq(req)
                    }.start()

                }
                override fun onError(e: Throwable?) {
                    super.onError(e)
                }
            }))
        }
    }


    override fun loadData() {
        super.loadData()

        setCommonTitle("订单确认")


        listAdapter = OrderConfirmListAdapter(R.layout.item_order_confirm,datas)
        mRootView.rv_order_confirm.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = listAdapter
        }

        mRootView.cl_address_area?.setOnClickListener {
            addFragment(MyAddressListFragment())
        }

        mRootView.tv_order_confirm_pay.setOnClickListener {
            createOrder()
        }

        loadDefaultAddress()
    }

    /**
     * 加载默认地址
     */
    fun loadDefaultAddress(){
        addSubscribe(RetrofitHelper.getInstance().addressApi.getDefaultAddress((HashMap<String, Any>().apply {
            this["pageSize"] = 20
        })).compose<AddressBeanVo>(RxHelper.defaultHandleResult<AddressBeanVo>()).subscribe(object : ProgressSubscriber<AddressBeanVo>(context){
            override fun onSucc(t: AddressBeanVo) {
                addressBeanVo.address = t?.city +  t?.province + t?.district + t?.detailAddress
                addressBeanVo.id = t?.receivingAddressId.toString()
                addressBeanVo.name = t?.receiverName
                addressBeanVo.phone = t?.receiverPhone


                mRootView?.tv_order_detail_name?.text = t?.receiverName
                mRootView?.tv_order_detail_phone?.text = t?.receiverPhone
                mRootView?.tv_order_detail_address?.text = t?.city +  t?.province + t?.district + t?.detailAddress
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }
        }))
    }

}